from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest, JsonResponse

# Create your views here.
from django.template import loader
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from App.models import User


# 试图函数的第一个参数就是请求对象, 由django传递

def index(request):
    # request常用类型
    # get传承那的获取
    print(request.GET)  # 获取查询字典

    # 获取单一值
    print(request.GET.get('username'))  # 单值返回一个列表

    # 获取多个值
    print(request.GET.getlist('age'))  # 多值返回的是一个列表

    # post传参
    print(request.POST.get())
    print(request.POST.getlist())

    # 获取请求方法
    print(request.method)

    # 获取请求路径
    print(request.path)

    # 其他请求属性
    print(request.META)
    '''
    META中的属性
    REMOTE_ADDR: 客户端地址
    REMOTE_HOST: 客户端主机
    HTTP_REFERER: 来源页面
    '''
    return HttpResponse("Hello World")


def home(request):
    # 查询数据库
    users = User.objects.all()
    loader.get_template("")
    return render(request, "index.html", context={"title": "wzxDjango", "name": "WZX", "users": users})
    # return HttpResponse("首页")


def age(request, age):
    return HttpResponse(age)


def list_user(request, name):
    return HttpResponse(name)


def date(request, date):
    return HttpResponse(date)


def get_phone(request, phone):
    return HttpResponse(phone)


def redir(request):
    return HttpResponseRedirect("/login")


def login(request):
    return render(request, 'login.html')


def test(request):
    return redirect("login/")


def variable(request):
    # 只支持Python内置对象, 且访问的时候只能用`.`的方式, 不能通过下标访问(可连续用`.`)
    num = 10
    name = "hello"
    students = [10, 11, 12, 13]
    student_dict = {'name': '内马尔', 'age': 39}
    return render(request, "variable.html", context=locals())


def filter(request):
    num = 10

    return render(request, "filter.html", context=locals())


def ajax(request):
    return render(request, 'ajax.html')


def ajaxs(request):
    if request.is_ajax():
        return JsonResponse({'code': 0, 'msg': 'success'})
    return render(request, 'ajax.html')


def myindex(request):
    return render(request, 'myindex.html')


def myreverse(request):
    return redirect(reverse('App:variable'))


# 处理注册
# 局部不检测csrf
# @csrf_exempt
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username, password)
    return JsonResponse({'code': 0, 'msg': 'success'})


def registers(request):
    return render(request, 'register.html')


def include(request):
    return render(request, 'include.html')
